package com.example.lightsmoking

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.util.Log
import android.widget.RemoteViews


/**
 * kotlin library {0} was
 * Implementation of App Widget functionality.
 */
class LightSmokingWidget : AppWidgetProvider() {
    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onEnabled(context: Context) {
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        // Enter relevant functionality for when the last widget is disabled
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        Log.v("light","onReceive")
        context?.let {
            when (intent?.action) {
                ACTION_REFRESH -> {
                    //
                    val count = intent.getIntExtra(ACTION_ADD_INTENT_KEY_COUNT, 0)
                    val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
                    sp.edit().putInt(SP_KEY_COUNT, count).apply()

                    Log.v("light","onReceive:${sp.getInt(SP_KEY_COUNT, -1)}")
                    //
                    updateAppWidget(context)

                }
            }
        }
    }
}

const val ACTION_REFRESH = "light.smoking.ACTION_REFRESH"
const val SP_NAME = "light-smoking"
const val SP_KEY_COUNT = "count"
const val ACTION_ADD_INTENT_KEY_COUNT = "ACTION_ADD_INTENT_KEY_COUNT"

internal fun updateAppWidget(context: Context) {
    // Construct the RemoteViews object
    val views = createRemoteViews(context)

    val componentName = ComponentName(context, LightSmokingWidget::class.java)
    AppWidgetManager.getInstance(context).updateAppWidget(componentName, views)
}

internal fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
    // Construct the RemoteViews object
    val views = createRemoteViews(context)

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views)
}

private fun createRemoteViews(context: Context): RemoteViews {
    val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
    val count = sp.getInt(SP_KEY_COUNT, 0)

    val bean = compute(count)

    val views = RemoteViews(context.packageName, R.layout.light_smoking_widget)
    val bitmapWidgetBg = BitmapFactory.decodeResource(context.resources, R.drawable.ic_widget_bg)
    views.setImageViewBitmap(R.id.ivWidgetBg, bitmapWidgetBg)

    views.setTextViewText(R.id.tvThing, context.resources.getText(R.string.nicotine))
    views.setTextViewText(R.id.tvLevel, "${bean.level}ml")
    views.setTextViewText(R.id.tvCount, "${bean.count}")

    val bitmapIcon = BitmapFactory.decodeResource(context.resources, R.drawable.ic_smoke);
    views.setImageViewBitmap(R.id.ivIcon, bitmapIcon)

    val bitmapState = BitmapFactory.decodeResource(context.resources, bean.lungStateBitmapResId)
    views.setImageViewBitmap(R.id.ivState, bitmapState)

    val bitmapAdd = BitmapFactory.decodeResource(context.resources, R.drawable.ic_widget_add);
    views.setImageViewBitmap(R.id.ivAdd, bitmapAdd)
    val intentAdd = Intent(context, LightSmokingWidget::class.java)
    intentAdd.action = ACTION_REFRESH
    intentAdd.putExtra(ACTION_ADD_INTENT_KEY_COUNT, bean.count + 1)
    val pendingIntentAdd = PendingIntent.getBroadcast(context, 1, intentAdd,  PendingIntent.FLAG_UPDATE_CURRENT)
    views.setOnClickPendingIntent(R.id.ivAdd, pendingIntentAdd)

    val intent = Intent(context, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
    views.setOnClickPendingIntent(R.id.ivWidgetBg, pendingIntent)
    return views
}

private fun compute(count: Int): WidgetBean {
    return WidgetBean(
        count * 4, when {
            count < 10 -> R.drawable.ic_lung_1
            count < 20 -> R.drawable.ic_lung_2
            count < 30 -> R.drawable.ic_lung_3
            count < 40 -> R.drawable.ic_lung_4
            count < 50 -> R.drawable.ic_lung_5
            count < 60 -> R.drawable.ic_lung_6
            count < 70 -> R.drawable.ic_lung_7
            count < 90 -> R.drawable.ic_lung_8
            else -> R.drawable.ic_lung_9
        }, count
    )
}

data class WidgetBean(val level: Int, val lungStateBitmapResId: Int, val count: Int)